{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_embedded,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "        \n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 4339,  1876,  9014, 11717, 11717, 11717, 15753, 15753, 15753,\n",
       "         15753,  4605,  4605,  4605,  4605, 22586, 22586, 22586, 22586,\n",
       "         19122, 19122,  2038, 13432, 13432, 13432,  1221,  1221, 12985,\n",
       "         12985, 12985, 28363,  6470,  2202,  2202, 11028, 11028, 13253,\n",
       "          8829, 24849, 24849,  7118,  7118,  7118,  7118, 15194, 15194,\n",
       "         20280, 20280, 15194, 29661, 29661, 15320, 29661, 15320, 12648,\n",
       "         12648, 12648, 12648, 12648, 16292, 16292, 16292, 16292,  6454,\n",
       "          6454, 13379, 13379,  3862,  3862,  3862,  3862, 19532,  1910],\n",
       "        [14882, 14882, 14882, 24400, 17865, 26020, 26020, 22443, 12389,\n",
       "         12389, 12389, 28876, 14998, 14998, 12973, 12973, 24198, 24198,\n",
       "         13693, 19200,   320,   320, 21229, 18734, 18734, 27689,  2162,\n",
       "         21474, 27705, 27705, 13538, 13538, 25752, 25752, 25752, 25752,\n",
       "          6927,  3657,  3657,  3657,  7357,  7357, 13991, 13991, 13991,\n",
       "         13991, 16511, 16511, 16511, 16511, 18389,  9395,  9395,    65,\n",
       "            65,    65,    65,    65,    65, 31071, 23053, 23053, 23053,\n",
       "         23053, 14868, 21129, 21129, 21129, 21129,  4810,  4810,  4810],\n",
       "        [19283, 11746, 11746, 10581, 10916, 14548,   152,   152,   152,\n",
       "         29980, 29980,  8162,  8162, 18710, 18710, 18710, 18710,  8885,\n",
       "          8885,  9488,  9488,  9488,  9488,  9488,  3611, 19408, 14450,\n",
       "         14450, 14450, 16338,  9324,  9324,  9324, 15787, 28008, 28008,\n",
       "         20413,  4200,  4200,  4200, 25092, 25092, 24267, 24267, 24267,\n",
       "         14633, 14633, 12156, 12156,  1748,  4142,  4142,  4142,  7824,\n",
       "          7824,  7624, 27562,  9829,  9829,  9829, 25306, 10663, 14430,\n",
       "         14430, 14430, 14430, 14430,  1485, 28775, 28775, 28775, 28775],\n",
       "        [ 9010,  9010, 30614, 30614,  7426,  7426,  5279, 30910, 30910,\n",
       "          1141,  1141,   297,   297, 22346,  4652,  4652,  7795,  5813,\n",
       "         23624,  5614, 23624,  3705, 10906, 18198, 15156, 30139, 30139,\n",
       "          2742,  2742, 23242, 23242, 30524,  4219, 28196, 28196,  3335,\n",
       "          3335, 21167, 21167, 21167,  4782,  4782, 24931, 24931, 24931,\n",
       "         15266, 15266, 15266,  2976, 29479, 25284, 29479, 29479,   361,\n",
       "         21583, 12288, 26061, 26061, 12581, 12976, 26061,  1023,  1023,\n",
       "         20414, 22083, 22286, 20682, 20682, 20682, 20682, 20682,  7765],\n",
       "        [21372, 21372, 26244,  9332,  9332,  9332, 24486, 21308, 21308,\n",
       "         21308, 21308, 21308, 29422, 29422, 29422, 25367, 25367, 25367,\n",
       "         11872, 29999, 11872, 29999, 17294, 19622, 19622, 19622, 16706,\n",
       "         16706, 16706,  8577,  8577, 16803, 17517, 17517, 17517, 17517,\n",
       "           882,   882,   882,   882, 10969, 10969, 10969, 10969, 13280,\n",
       "         14325, 13280, 14325,  8818,  8818, 28286, 28286, 28286, 28286,\n",
       "         15013, 15013, 20119, 20119, 14983, 14983, 14983, 26374, 26374,\n",
       "         26374, 26374, 18198, 18198, 18198,  9687,   400,   400, 31251],\n",
       "        [21642, 11824, 21642, 22898, 22898, 22898,   309,   309, 21418,\n",
       "         12175, 12175, 14445, 14445, 29484, 29484, 22806,  8874,  8874,\n",
       "          8874,  8874, 31275, 31275, 31275, 21320, 21320, 21320, 20317,\n",
       "         20317,  6039,  6039,  6039,  6039,  6039,  4496,  4496,  5026,\n",
       "          5026,  5026,  5026, 21488,  6438,  6438,  6438, 13792, 13792,\n",
       "         13792, 21101, 21101, 21101, 28488, 28488, 28488, 28488, 28488,\n",
       "         28488, 18929,  2047,  2047,  2047,  2047, 10644, 10644, 30708,\n",
       "         30708, 30708, 26584, 25651, 15400, 15400, 15400, 25651, 25651],\n",
       "        [31492, 26949, 16555, 24015, 21365, 30205, 30205, 26065, 26065,\n",
       "         20325, 23564, 17687, 12023, 12023, 13855, 13855, 13855, 13855,\n",
       "         12023,  4369,  4369, 10998, 10998, 14720, 14720, 16237, 16237,\n",
       "         16237, 16237, 16237, 15944, 15944,  8649,  8649, 31473,  7057,\n",
       "          7057,  7057,  7057, 12464, 12464, 12464, 12464, 12464, 20706,\n",
       "         24891, 24891, 20706,  1328,  1328,  4919,  4919,  8093, 30015,\n",
       "         24188, 20618, 20687, 21216, 21216, 26429, 26429, 26429, 26429,\n",
       "         29491, 22973, 20968, 15618, 20968, 14601,  4976, 20011, 17397],\n",
       "        [28173, 28173, 29119,  9357, 30232, 27389, 25008, 25008, 10107,\n",
       "         10107, 28532, 19256, 26673, 26673, 21079,   455,  1574, 30760,\n",
       "         30760, 27333, 15881, 15881, 11589, 24626, 24626,  8875,  8875,\n",
       "          8875,  8009,  9257,  9257, 13632, 13632, 26901, 21366, 26901,\n",
       "          9797, 17973, 17973, 17042,  7373, 19834, 19834, 19834, 30268,\n",
       "         21169, 18190, 18190, 24022, 24022, 24022, 30089, 30089, 30089,\n",
       "          3825,  3825,  3825,  3825,  3190,  3190, 28386, 28386, 26011,\n",
       "         26011,  7722,  7722,  7722,  3582,  3582, 30216, 30216, 30216],\n",
       "        [18650, 14565, 14565,  2391, 11571, 11571, 27061, 27061, 21426,\n",
       "          5087,  5087,  5087,  5087, 20237, 24943, 24943, 12513, 12513,\n",
       "         12513, 12513,  8223,  1625, 29974, 19518, 19518,  7722,  7722,\n",
       "          7722,  7722, 11916, 11916, 11916, 11916, 25395, 25395, 25395,\n",
       "         14005, 14005, 11635, 11635, 10501, 11635, 13248, 21330,  5762,\n",
       "          5762,  5762, 26014, 21902, 21902,  3041, 31341, 31341, 31341,\n",
       "         23214, 23214,  6311,  6311, 13578, 17559, 17559, 23214, 28568,\n",
       "         28568, 12763, 28568,  7793, 27030, 17518, 17518, 27520, 22779],\n",
       "        [19035, 19035, 10493, 10493,  1213,  1213, 21578, 21578, 15312,\n",
       "         28399, 20919, 10355, 20919, 10355,  8429, 19064, 31783, 31783,\n",
       "         31783, 31783, 31783,  1266,  1266, 29805, 28008, 28008, 28008,\n",
       "          9048,  9048,  9048,  9048,  5167,  5167, 25738, 25738, 28421,\n",
       "         28421, 28421, 24520, 28488, 28488, 28488, 31355,  5373,  5373,\n",
       "         15397, 15397, 15397, 22291, 22291,   638,   638,   638, 29395,\n",
       "         29395, 29395, 29395, 12870, 13745, 13745, 13745, 13745,  2405,\n",
       "          3287, 13628, 13628, 15595, 15595, 15595, 15595, 15595,  3681]],\n",
       "       dtype=int32), 10.373779, 0.0]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.199, cost=5.13]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.87it/s, accuracy=0.215, cost=4.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.124831, training avg acc 0.151039\n",
      "epoch 1, testing avg loss 4.981848, testing avg acc 0.220418\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:21<00:00,  2.29it/s, accuracy=0.265, cost=4.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.328, cost=3.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.619548, training avg acc 0.250447\n",
      "epoch 2, testing avg loss 4.369691, testing avg acc 0.274158\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:23<00:00,  2.29it/s, accuracy=0.299, cost=3.92]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.333, cost=3.7] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 4.091566, training avg acc 0.295998\n",
      "epoch 3, testing avg loss 4.050441, testing avg acc 0.305012\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:21<00:00,  2.29it/s, accuracy=0.343, cost=3.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.376, cost=3.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.736866, training avg acc 0.330743\n",
      "epoch 4, testing avg loss 3.859153, testing avg acc 0.327623\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:11<00:00,  2.33it/s, accuracy=0.375, cost=3.23]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.403, cost=3.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 3.472547, training avg acc 0.358198\n",
      "epoch 5, testing avg loss 3.750740, testing avg acc 0.340661\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:10<00:00,  2.33it/s, accuracy=0.406, cost=2.97]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.371, cost=3.38]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 3.264357, training avg acc 0.380809\n",
      "epoch 6, testing avg loss 3.689242, testing avg acc 0.346827\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:11<00:00,  2.33it/s, accuracy=0.431, cost=2.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.00it/s, accuracy=0.366, cost=3.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 3.088567, training avg acc 0.401044\n",
      "epoch 7, testing avg loss 3.655719, testing avg acc 0.352409\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:16<00:00,  2.31it/s, accuracy=0.472, cost=2.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.382, cost=3.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 2.943453, training avg acc 0.418657\n",
      "epoch 8, testing avg loss 3.644395, testing avg acc 0.355638\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:13<00:00,  2.32it/s, accuracy=0.507, cost=2.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.382, cost=3.29]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 2.811881, training avg acc 0.435594\n",
      "epoch 9, testing avg loss 3.646702, testing avg acc 0.357813\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.533, cost=2.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.392, cost=3.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 2.694221, training avg acc 0.451318\n",
      "epoch 10, testing avg loss 3.663233, testing avg acc 0.358267\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.32it/s, accuracy=0.555, cost=2.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.392, cost=3.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 2.594566, training avg acc 0.465128\n",
      "epoch 11, testing avg loss 3.681935, testing avg acc 0.358460\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:12<00:00,  2.32it/s, accuracy=0.585, cost=1.95]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.414, cost=3.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 2.516286, training avg acc 0.475958\n",
      "epoch 12, testing avg loss 3.703498, testing avg acc 0.358425\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:11<00:00,  2.33it/s, accuracy=0.609, cost=1.8] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.08it/s, accuracy=0.409, cost=3.38]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 2.412441, training avg acc 0.492302\n",
      "epoch 13, testing avg loss 3.739242, testing avg acc 0.356440\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:03<00:00,  2.36it/s, accuracy=0.615, cost=1.72]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.08it/s, accuracy=0.409, cost=3.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 2.320951, training avg acc 0.506907\n",
      "epoch 14, testing avg loss 3.781036, testing avg acc 0.355030\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:03<00:00,  2.36it/s, accuracy=0.642, cost=1.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.409, cost=3.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 2.251104, training avg acc 0.517634\n",
      "epoch 15, testing avg loss 3.821990, testing avg acc 0.354338\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:03<00:00,  2.35it/s, accuracy=0.655, cost=1.54]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.376, cost=3.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 2.187097, training avg acc 0.527825\n",
      "epoch 16, testing avg loss 3.870126, testing avg acc 0.355160\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:03<00:00,  2.35it/s, accuracy=0.666, cost=1.48]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.05it/s, accuracy=0.403, cost=3.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 2.141544, training avg acc 0.534170\n",
      "epoch 17, testing avg loss 3.913723, testing avg acc 0.354277\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:04<00:00,  2.35it/s, accuracy=0.679, cost=1.44]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.06it/s, accuracy=0.398, cost=3.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 2.073942, training avg acc 0.545887\n",
      "epoch 18, testing avg loss 3.956338, testing avg acc 0.351603\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:55<00:00,  2.38it/s, accuracy=0.72, cost=1.31] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.15it/s, accuracy=0.409, cost=3.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 2.007271, training avg acc 0.557702\n",
      "epoch 19, testing avg loss 4.002933, testing avg acc 0.350163\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:52<00:00,  2.39it/s, accuracy=0.715, cost=1.25]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.01it/s, accuracy=0.43, cost=3.46] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.937211, training avg acc 0.570857\n",
      "epoch 20, testing avg loss 4.059728, testing avg acc 0.348385\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:17<00:00,  2.25it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.052993"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
